package com.zhx.common.common.event.Listener;


import com.zhx.common.common.event.UserOnlineEvent;
import com.zhx.common.user.dao.UserDao;
import com.zhx.common.user.domain.entity.User;
import com.zhx.common.user.domain.enums.UserActiveStatusEnum;
import com.zhx.common.user.service.IpService;
import com.zhx.common.user.service.adapter.WSAdapter;
import com.zhx.common.user.service.cache.UserCache;
import com.zhx.common.user.service.impl.PushService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

@Component
@Slf4j
public class UserOnlineListener {


    @Resource
    private UserDao userDao;

    @Resource
    private IpService ipService;

    @Resource
    private UserCache userCache;

    @Resource
    private PushService pushService;

    @Autowired
    private WSAdapter wsAdapter;

    /**
     * fallbackExecution = true 如果没有运行事务，是否应该处理该事件
     */
    @TransactionalEventListener(classes = UserOnlineEvent.class, phase = TransactionPhase.AFTER_COMMIT,fallbackExecution = true)
    public void saveDB(UserOnlineEvent event) {

        User user = event.getUser();
        User update = new User();

        //更新用户信息
        update.setId(user.getId());
        update.setLastOptTime(user.getLastOptTime());
        update.setIpInfo(user.getIpInfo());
        update.setActiveStatus(UserActiveStatusEnum.ONLINE.getStatus());
        userDao.updateById(update);

        //用户ip详情的更新
        ipService.refreshIpDetailAsync(user.getId());
        log.info("用户ip更新成功");
    }


    @Async
    @EventListener(classes = UserOnlineEvent.class)
    public void saveRedisAndPush(UserOnlineEvent userOnlineEvent){
        User user = userOnlineEvent.getUser();
        userCache.online(user.getId(), user.getLastOptTime());
        //推送给所有用户，该用户登录成功
        pushService.sendPushMsg(wsAdapter.buildOnlineNotifyResp(userOnlineEvent.getUser()));
    }
}
